<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import {LoginStore} from "../stores";
import {
  CaptchaImg,
  LoginService,
  SmsmobileService,
  CustomRegistService
} from '@/api/Login.js'
import router from "../router";

const loading = ref(false)
const isRegister = ref(false)
// pinia实例化
const store = LoginStore()
// 登录对话框
const formModel = ref({
  username: '',
  mobile: '',
  password: '',
  repassword: '',
  mobile_captcha: '',
  captcha: '',
})
// 验证码相关信息
const captchaImage = reactive({
  captchaID: '',
  captchaImg: ''
})
const getImgCaptcha = async () => {
  const res = await CaptchaImg()
  captchaImage.captchaImg = res.data.image_base
  captchaImage.captchaID = res.data.key
}
onMounted(() => {
  getImgCaptcha()
})

// 整个表单的校验规则
const rules = {
  username: [
    // 非空校验 required:true,  message消息提示,  trigger:触发时机 blue:失焦时触发，
    {required: true, message: '请输入用户名', trigger: 'blur'},
    // 长度校验
    {min: 5, max: 10, message: '用户名必须是5到10位的字符', trigger: 'blur'},
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^\S{6,13}$/, message: '手机号必须是6-15位的非空字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入手机号'))
        } else {
          if (value !== '') {
            var reg = /^1[13456789]\d{9}$/;
            if (!reg.test(value)) {
              callback(new Error('手机号输入错误'))
            } else {
              //手机号码输入正确时才可点击获取验证码按钮
              mobileButton.getDisabled = false;
            }
          }
          callback();
        }
      }
    }
  ],
  mobile_captcha: [
    {required: true, message: '请输入手机号验证码', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur'}
  ],
  repassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur'},
    // 自定义校验
    {
      validator: (rule, value, callback) => {
        // rule:当前校验规则的相关信息
        // value:所校验的表单元素目前的表单值
        // callback:回调结果信息 callback()校验成功
        //                     callback(new Error(错误信息)) 校验失败
        // 无论成功失败都要调用callback
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
    }
  ],
  captcha: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
  ],
}
const form = ref()
const login = (form) => {
  if (!form) return;
  form.validate((valid) => {
    if (valid) {
      loading.value = true
      // 登录
      setTimeout(async () => {
        try {
          const LoginData = {
            ...formModel.value
          }
          // console.log(LoginData)
          await LoginService(LoginData)
              .then((res) => {
                console.log('来了没')
                router.push({path: '/'})
                // console.log(res)
                store.$state.access_id = res.data.userId
                store.$state.access_username = res.data.username
                store.$state.access_token = res.data.token
              })
        } catch (error) {
          console.log('登录失败', error)
          router.push({path: '/login'})
        } finally {
          loading.value = false
        }
      }, 2000)
    } else {
      return false
    }
  })
}

// 切换的时候，重置表单内容
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: '',
    mobile_captcha: '',
    captcha: '',
  }
})

// 注册模块的相关功能

// 手机验证码按钮
const mobileButton = reactive({
  buttonName: '点击获取验证码',
  countDownTime: 60,
  getDisabled: false,
  time: null
})
const waitTime = async (val) => {
  let startTime = localStorage.getItem('startTimeLogin');
  let nowTime = new Date().getTime();
  if (startTime) {
    let surplus = 60 - parseInt((nowTime - startTime) / 1000, 10);
    mobileButton.countDownTime = surplus <= 0 ? 0 : surplus;
  } else {
    mobileButton.countDownTime = 60;
    localStorage.setItem('startTimeLogin', nowTime);
  }

  console.log(val)
  if (val) {
    await SmsmobileService(val)
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
  } else {
    ElMessage.error('请输入手机号')
  }
  mobileButton.time = setInterval(() => {
    mobileButton.countDownTime--
    mobileButton.getDisabled = true
    if (mobileButton.countDownTime <= 0) {
      localStorage.removeItem('startTimeLogin')
      clearInterval(mobileButton.time)
      mobileButton.countDownTime = 60
      mobileButton.getDisabled = false
    }
  }, 1000)
}
// 注册
const register = (form) => {
  if (!form) return;
  form.validate((valid) => {
    if (valid) {
      loading.value = true;
      setTimeout(async () => {
        try {
          await CustomRegistService(formModel.value);
          await router.push({path: '/customlogin'})
        } catch (error) {
          console.error('登录失败:', error);
        } finally {
          loading.value = false; // 在登录成功或失败后，将 loading 值设回 false。
        }
      }, 1000);
    } else {
      console.log('error submit!');
      return false;
    }
  });
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="6" :offset="9">
      <!--      注册相关表单    -->
      <el-form id="form_register" ref="form" size="large" autocomplete="off" v-if="isRegister" :model="formModel"
               :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="mobile">
          <el-input v-model="formModel.mobile" :prefix-icon="Phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
              :prefix-icon="Lock"
              type="password"
              placeholder="请再次输入密码"
              v-model="formModel.repassword"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobile_captcha">
          <span>
            <el-input
                :prefix-icon="Lock"
                placeholder="请输入手机验证码"
                v-model="formModel.mobile_captcha"
            ></el-input>
          </span>
          <span style="margin-left: 10px">
            <el-button @click="waitTime(formModel.mobile)" v-if="!mobileButton.getDisabled"
                       :loading="loading">{{ mobileButton.buttonName }}</el-button>
            <el-button disable="true" v-if="mobileButton.getDisabled">倒计时{{ mobileButton.countDownTime }}s</el-button>
          </span>
        </el-form-item>
        <el-form-item>
          <el-button @click="register(form)" v-loading="loading" class="button" type="primary" auto-insert-space>
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!--      登录相关表单    -->
      <el-form id="form" :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off" v-else>
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="formModel.password"
              name="password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="input-with-image">
            <el-input
                v-model="formModel.captcha"
                :prefix-icon="Lock"
                type="text"
                placeholder="请输入验证码"
            ></el-input>
            <el-image :src="captchaImage.captchaImg" style="width:60%;margin-left:30px"></el-image>
          </div>

        </el-form-item>
        <el-form-item>
          <el-button class="button" v-loading="loading" type="primary" auto-insert-space @click="login(form)"
          >登录
          </el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped>
.input-with-image {
  display: flex;
  align-items: center;
}
/* Background styling for the left column */
.login-page {
  height: 100%;
  width: 100%;
  background: url("@/assets/image/background.jpg");
  border-radius: 0 20px 20px 0;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: fixed;
  top: 0px;
  left: 0px;
  /*z-index: -1;*/
}

/* Form styling for the right column */
#form {
  position: relative;
  top: 25%;
  border: 1px blue;
  background: white;
  width: 450px;
  height: 55%;
  border-radius: 15px 15px 15px 15px;
  opacity: 0.8;
}

#form h1 {
  margin: 0 auto;
  margin-top: 30px;
}

#form .el-form-item {
  width: 80%;
  margin-left: 40px;
}

#form_register {
  position: relative;
  border: 1px blue;
  top: 15%;
  background: white;
  width: 450px;
  height: 72%;
  border-radius: 15px 15px 15px 15px;
  opacity: 0.8;
}

#form_register h1 {
  margin: 0 auto;
  margin-top: 30px;
}

#form_register .el-form-item {
  width: 80%;
  margin-left: 40px;
}


</style>